package com.yhos.platform.oopston.core.web;

import com.alibaba.fastjson.JSONObject;
import com.yhos.platform.oopston.core.dto.BaseOrderCreateRequestDTO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对于创建订单的请求路由进行渠道参数的解析并放入Header中
 */
@WebFilter(filterName = "bodyReaderFilter", urlPatterns = "/api/order/create")
public class BodyReaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            HttpServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            String body = HttpUtil.getBodyString(requestWrapper);
            BaseOrderCreateRequestDTO requestObject = JSONObject.parseObject(body, BaseOrderCreateRequestDTO.class);
            requestWrapper.setAttribute("channelType", requestObject.getChannelType());
            filterChain.doFilter(requestWrapper, response);
            return ;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
